package com.yksj.healthtalk.ui.salon;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;

import com.yksj.healthtalk.adapter.FriendAdapter;
import com.yksj.healthtalk.adapter.FriendAdapter.onClickFriendAttentionListener;
import com.yksj.healthtalk.adapter.FriendAdapter.onClickFriendHeadListener;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.friend.FriendInformUI;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.PersonInfoUtil;
import com.yksj.healthtalk.utils.PopWindowUtil;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 话题成员列表
 * @author Administrator
 *
 */
public class SalonMemberListActivity extends BaseFragmentActivity implements OnClickListener,OnItemClickListener,onClickFriendHeadListener,onClickFriendAttentionListener{
	
	private PullToRefreshListView mPullToRefreshListView;
	private ListView mListView;
	private FriendAdapter mBaseAdapter;
	private ArrayList<CustomerInfoEntity> entities;//数据源
	private String groupId;
	private int flag; //表示是查询 话题成员  还是 在线成员 , 0 则是 话题成员 1000是 在线成员
	private int pageSize = 1;
	private PopWindowUtil popWindowUtil;
	private PopupWindow mPopBottom;
	private String type = "0";
	private boolean isFirstReq = true;//标记是否是第一次请求
	
	private BroadcastReceiver  mBroadcastReceiver = new BroadcastReceiver(){
		public void onReceive(Context context, Intent intent) {
			final String action = intent.getAction();
			if(MessagePushService.ACTION_CHATTINGONLINEFRIEND.equals(action)){//在线成员
				Serializable result = intent.getSerializableExtra(MessagePushService.BROAD_KEY);
				if (result != null) {
					entities.addAll((ArrayList<CustomerInfoEntity>)result);
					mSetnotifyData();
					LodingFragmentDialog.dismiss(getSupportFragmentManager());
				}
			}
		};
	};
	private View mSpliteLine;
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.salon_member);
		initView();
		initDate();
	}
	
	private void initDate() {
		//接受数据
		Intent intent = getIntent();
		if (intent.hasExtra("groupId")) {
			groupId =  (String) intent.getExtras().get("groupId");
			//114656
		}
		if (intent.hasExtra("type")) {
			flag = (Integer) intent.getExtras().get("type");
		}
		entities = new ArrayList<CustomerInfoEntity>();
		if(flag == 1000){
			titleTextV.setText("在线成员");
		}else{
			titleTextV.setText("话题成员");
		}
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.setOnItemClickListener(this);
		mBaseAdapter = new FriendAdapter(getApplicationContext(), entities);
		mBaseAdapter.setonClickFriendHeadListener(this);
		mBaseAdapter.setonClickFriendAttentionListener(this);
		mBaseAdapter.setIsSalonMemberList(true);
		mListView.setAdapter(mBaseAdapter);
		mSpliteLine = LayoutInflater.from(this).inflate(R.layout.list_line_layout, null);
	}
	
	private void initView() {
		initTitle();
		mPullToRefreshListView = (PullToRefreshListView) findViewById(R.id.hall);
		titleLeftBtn.setOnClickListener(this);
	}
	
	/**
	 * 获取在线成员
	 */
	private void onReqChattingOnlineFriends() {
		SmartFoxClient.getChattingOnlineFriends(groupId);
	}
	
	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter(MessagePushService.ACTION_CHATTINGONLINEFRIEND);
		registerReceiver(mBroadcastReceiver,filter);
		if(isFirstReq){
			if(flag == 1000){
				onReqChattingOnlineFriends();//获取在线成员
			}else{
				getMembers(type);//获取话题成员
				mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						if (groupId == null) {
							ToastUtil.showShort(getApplicationContext(),"传值失败");
							return;
						}else if(SmartFoxClient.getLoginUserId().equals("")){
							ToastUtil.showShort(getApplicationContext(),"与服务器连接失败");
							return;
						}
						getMembers(type);
					}
				});
			}
		}
		isFirstReq = false;
		super.onStart();
	}
	
	@Override
	protected void onStop() {
		unregisterReceiver(mBroadcastReceiver);
		super.onStop();
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.title_right:
			showMenu(v);
			break;
		case R.id.all:
			if(mPopBottom.isShowing()){
				mPopBottom.dismiss();
			}
			type="0";
			pageSize =1;
			entities.clear();
			getMembers(type);
			break;
		case R.id.day_ticket:
			if(mPopBottom.isShowing()){
				mPopBottom.dismiss();
			}
			type="1";
			pageSize =1;
			entities.clear();
			getMembers(type);
			break;
		case R.id.month_ticket:
			if(mPopBottom.isShowing()){
				mPopBottom.dismiss();
			}
			type="2";
			pageSize =1;
			entities.clear();
			getMembers(type);
			break;
		case R.id.other:
			if(mPopBottom.isShowing()){
				mPopBottom.dismiss();
			}
			type="3";
			pageSize =1;
			entities.clear();
			getMembers(type);
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		FriendHttpUtil.onItemClick(this, entities.get(position-1));
	}
	
	/**
	 * pop的显示
	 * @param view
	 */
	private void showMenu(View view){
		if(mPopBottom == null){
			LayoutInflater inflater = LayoutInflater.from(this);
			View v = inflater.inflate(R.layout.salon_meber_pop_top,null);
			mPopBottom = new PopupWindow(v,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,true);
			mPopBottom.setBackgroundDrawable(new BitmapDrawable());
			mPopBottom.setFocusable(true);
			RadioGroup radioGroup = (RadioGroup)v.findViewById(R.id.radiogroup);
			int count = radioGroup.getChildCount();
			for (int i = 0; i < count; i++) {
				radioGroup.getChildAt(i).setOnClickListener(this);
			}
		}else if(mPopBottom.isShowing()){
			mPopBottom.dismiss();
			return;
		}
		mPopBottom.showAsDropDown(view);
	}

	@Override
	public void onClickFriendAttention(int attentioned,
			final CustomerInfoEntity entity, int positon) {
		if (groupId.equals("")) {
			ToastUtil.showShort(getApplicationContext(), "值传递失败,请重新操作");
			return;
		}
		HttpRestClient.doHttpBuyTicketsRecords(groupId,entity.getId(), new AsyncHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, String content) {
				try {
					JSONArray jsonArray = new JSONArray(content.toString());
					JSONObject object = (JSONObject) jsonArray.get(0);
//					String beginTime = object.getString("begin_Time");
					String buy_Time = object.getString("buy_Time");
					String end_Time = object.getString("end_Time");
					String ticketType = object.getString("ticket_Type");
					if (popWindowUtil == null) {
						 popWindowUtil = new PopWindowUtil(getApplicationContext());	
					}
					if (mBaseAdapter.getClickView() ==null) {
						ToastUtil.showShort(getApplicationContext(), "传值失败");
						return;
					}
					popWindowUtil.showPopMenu(mBaseAdapter.getClickView(), entity.getName() ,buy_Time, end_Time, Integer.valueOf(ticketType));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}

	@Override
	public void onClickFriendHead(CustomerInfoEntity entity, int positon) {
		PersonInfoUtil.choiceActivity(entity.getId(), this,String.valueOf(entity.getRoldid()) );
	}
	
	/**
	 * 获取成员列表
	 * @param type
	 */
	private void getMembers(String type) {
		HttpRestClient.doHttpSalonMembers(groupId,SmartFoxClient.getLoginUserId(),
				String.valueOf(pageSize++), String.valueOf(20),type, 
			new ObjectHttpResponseHandler(this) {
			@Override
			public Object onParseResponse(String content) {
				List<CustomerInfoEntity>  infoEntities = FriendHttpUtil.jsonAnalysisFriendEntity(content,true);
				return infoEntities;
			}
			@Override
			public void onSuccess(int statusCode, Object response) {
				if(response != null){
					entities.addAll((Collection<? extends CustomerInfoEntity>) response);
					mSetnotifyData();
				}
			}
			@Override
			public void onFinish() {
				super.onFinish();
				mPullToRefreshListView.onRefreshComplete();
			}
		});
	}

	private void mSetnotifyData(){
		mListView.removeFooterView(mSpliteLine);
		mListView.addFooterView(mSpliteLine);
		mBaseAdapter.notifyDataSetChanged();
	}
	
}
